import cm_client

from app.bigdata.handlers.cm_handler import CM6
from core.logger import logger


class ClouderaMonitorHandler(CM6):
    def __init__(self):
        super().__init__()
        api_url = f"{self.protocol}://{self.host}:{self.port}/api/v19"
        self.api_client = cm_client.ApiClient(api_url)
        self.cluster_api_instance = cm_client.ClustersResourceApi(self.api_client)
        self.services_api_instance = cm_client.ServicesResourceApi(self.api_client)

    def get_clusters(self):
        api_response = self.cluster_api_instance.read_clusters(view='SUMMARY')
        clusters = []
        for cluster in api_response.items:
            clusters.append(cluster)
        return clusters

    def inspect_services(self, cluster):
        res = []
        services = self.services_api_instance.read_services(cluster, view='FULL')
        for service in services.items:
            for health_check in service.health_checks:
                if health_check.summary == 'BAD' or health_check.summary == 'CONCERNING':
                    res.append({"service_name": service.name, "health_check": health_check.name, "summary": health_check.summary})
                    logger.info(
                        f"cm_monitoring message => 告警服务: {service.name} 监控检查名称: {health_check.name} 服务状态: {health_check.summary}")
        return res


def check_service_status(obj):
    res = []
    clusters = obj.get_clusters()
    for cluster in clusters:
        inspect_service = obj.inspect_services(cluster.name)
        if inspect_service:
            res.extend(inspect_service)
    return res


if __name__ == '__main__':
    from pprint import pprint

    cloudera_monitor = ClouderaMonitorHandler()
    check_service_status = check_service_status(cloudera_monitor)
